package com.wxh.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wxh.dao.CheckGroupDao;
import com.wxh.entity.PageResult;
import com.wxh.entity.QueryPageBean;
import com.wxh.pojo.CheckGroup;
import com.wxh.service.CheckGroupService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    CheckGroupDao checkGroupDao;
    @Override
    public void add(CheckGroup checkGroup, Integer[] checkItemIds) {
        checkGroupDao.add(checkGroup);
        int checkgroupId = checkGroup.getId();
        setCheckgroupAndCheckItem(checkgroupId,checkItemIds);
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        int currentPage = queryPageBean.getCurrentPage();
        int pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<CheckGroup> checkGroups = checkGroupDao.pageQuery(queryString);
        PageResult pageResult = new PageResult(checkGroups.getTotal(), checkGroups.getResult());
        return pageResult;
    }

    @Override
    public CheckGroup findById(Integer checkGroupId) {
        return checkGroupDao.findById(checkGroupId);
    }

    @Override
    public List<Integer> findCheckItemIdsByCheckGroupId(Integer checkGroupId) {
        return checkGroupDao.findCheckItemIdsByCheckGroupId(checkGroupId);
    }

    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkItemIds) {
        checkGroupDao.edit(checkGroup);
        checkGroupDao.deleteAssociatoin(checkGroup.getId());
        setCheckgroupAndCheckItem(checkGroup.getId(),checkItemIds);
    }

    @Override
    public List<CheckGroup> findAll() {

        return checkGroupDao.findAll();
    }

    private void setCheckgroupAndCheckItem(int checkgroupId,Integer[] checkItemIds){
        if(checkItemIds!=null&&checkItemIds.length>0){
            for (Integer checkItemId : checkItemIds) {
                Map map = new HashMap();
                map.put("checkGroupId",checkgroupId);
                map.put("checkItemId",checkItemId);

                checkGroupDao.setCheckGroupAndCheckItem(map);
            }
        }
    }
}
